package com.yand.oratransmysql.service.impl;

import com.yand.oratransmysql.constant.Constant;
import com.yand.oratransmysql.entity.DataBaseConvert;
import com.yand.oratransmysql.entity.OracleTableInfoBean;
import com.yand.oratransmysql.service.DataBaseConvertSerive;
import com.yand.oratransmysql.service.OracleTableService;
import com.yand.oratransmysql.thread.DbConvertThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.*;

/**
 * 数据库迁移转换处理类
 */
@Service
public class DataBaseConvertHandle implements DataBaseConvertSerive {

    @Autowired
    private OracleTableService oracleTableService;

    @Autowired
    private MysqlServiceImpl mysqlService;

    /**
     * oracle表的处理逻辑：
     *  1，遍历该库中的所有表,
     *  2，传递表名称查询这个表的所有列与字段类型。
     *  3，查询这个表的所有值，
     *  4，根据查询出来的列与字段类型，写好mysql对应的insert 语句
     *  5，根据一个表一个文件的形式写到特定的文件夹下
     */
    @Override
    public void oralceTableHandle() {

        List<OracleTableInfoBean> oracleTableInfoBeanList = oracleTableService.queryAllTableName();

        CountDownLatch countDownLatch = new CountDownLatch(oracleTableInfoBeanList.size());

        /**
         * 自定义线程池的实现
         */
        ExecutorService  threadPool = new ThreadPoolExecutor(Constant.coreThreadNum, Integer.MAX_VALUE,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(Constant.blockqueueLenth));

        for(OracleTableInfoBean oracleTableInfoBean : oracleTableInfoBeanList){
            DataBaseConvert dataBaseConvert =  DataBaseConvert.builder()
                                     .tableName(oracleTableInfoBean.getTableName())
                                     .countDownLatch(countDownLatch)
                                     .mysqlService(mysqlService)
                                     .oracleTableService(oracleTableService)
                                     .build();
            //开启线程池进行处理
            threadPool.execute(DbConvertThreadFactory.createHandleThread(Constant.type,dataBaseConvert));
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        threadPool.shutdown();
        System.out.println("完成");

    }
}
